package com.kirayous.api.strategy.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.kirayous.api.strategy.UploadStrategy;
import com.kirayous.api.strategy.factory.UploadStrategyFactory;
import com.kirayous.api.strategy.template.AbstractUploadStrategyImpl;
import com.kirayous.common.properties.OssConfigProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;

/**
 * @author KiraYous
 * @version V1.0
 * @Package com.kirayous.api.strategy.impl
 * @date 2021/10/25 20:14
 */
@Service("ossUploadStrategyImpl")
public class OssUploadStrategyImpl implements AbstractUploadStrategyImpl {


    @Autowired
    OssConfigProperties ossConfigProperties;

    @Override
    public Boolean exists(String filePath) {
        return getOssClient().doesObjectExist(ossConfigProperties.getBucketName(), filePath);
    }

    @Override
    public void upload(String path, String fileName, InputStream inputStream) {
        getOssClient().putObject(ossConfigProperties.getBucketName(), path + fileName, inputStream);
    }

    @Override
    public String getFileAccessUrl(String filePath) {
        String ossUrl=ossConfigProperties.getUrl();
        if(!ossUrl.endsWith("/")){ossUrl=ossUrl+"/";}
        return ossUrl + filePath;
    }

    /**
     * 获取ossClient
     *
     * @return {@link OSS} ossClient
     */
    private OSS getOssClient() {
        return new OSSClientBuilder().build(ossConfigProperties.getEndpoint(), ossConfigProperties.getAccessKeyId(), ossConfigProperties.getAccessKeySecret());
    }



    //后置处理器，初始化完成bean 生成后会调用这个方法
    @Override
    public void afterPropertiesSet() throws Exception {
        Service serviceAno=this.getClass().getAnnotation(Service.class);
        UploadStrategyFactory.register(serviceAno.value(),this);
    }

}
